﻿using System.Collections;
using UnityEngine;
using YooAsset;
namespace LitFramework
{
    public class AssetState_DownloadFiles : IState
    {
        public StateMechine Master { get; set; }

        private ResourcePackage package;

        public void OnEnter(params object[] values)
        {
            GameManager.Instance.InitState = "HotUpdate DownloadFiles...";
            GameManager.Instance.InitProgress = 0;

            package = values[0] as ResourcePackage;
            GameManager.Instance.StartCoroutine(BeginDownload());
        }

        public void OnExit()
        {

        }

        public void OnUpdate()
        {

        }

        private IEnumerator BeginDownload()
        {
            yield return new WaitForEndOfFrame();

            int downloadingMaxNum = 10;
            int failedTryAgain = 3;
            var downloader = package.CreateResourceDownloader(downloadingMaxNum, failedTryAgain);

            if (downloader.TotalDownloadCount == 0)
            {
                Master.TurnToState<AssetState_UpdateOver>();
                yield break;
            }

            // 发现新更新文件后，挂起流程系统
            // 注意：开发者需要在下载前检测磁盘空间不足
            int totalDownloadCount = downloader.TotalDownloadCount;
            long totalDownloadBytes = downloader.TotalDownloadBytes;

            downloader.OnDownloadErrorCallback = OnDownloadError;
            downloader.OnDownloadProgressCallback = OnDownloadProgress;
            downloader.BeginDownload();
            yield return downloader;

            // 检测下载结果
            if (downloader.Status != EOperationStatus.Succeed)
                yield break;

            Master.TurnToState<AssetState_ClearCache>();
        }

        private void OnDownloadError(string fileName, string error)
        {
            TipPanel.ShowTip($"{fileName}:{error}", "好的", null);
        }

        private void OnDownloadProgress(int totalDownloadCount, int currentDownloadCount, long totalDownloadBytes, long currentDownloadBytes)
        {
            GameManager.Instance.InitState = $"HotUpdate DownloadFiles[{currentDownloadCount}/{totalDownloadCount}]...";
            GameManager.Instance.InitProgress = (float)currentDownloadBytes / totalDownloadBytes;
        }
    }
}